package com.zhongkeruan.user.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhongkeruan.user.service.IUserService;
import com.zhongkeruan.user.vo.User;

@Service
@Transactional
@CacheConfig(cacheNames = "users")
public class UserServiceImpl implements IUserService {
	@Autowired
	private com.zhongkeruan.user.jpa.UserRepository userRepository;

	@Override
	public User findByUsername(String username) throws Exception {
		return userRepository.findByUsername(username);
	}

	@Override
	@Cacheable(key = "'userAll'")
	public List<User> findAll() throws Exception {
		System.out.println("从数据库查询+=================================");
		return userRepository.findAll();
	}

	@Override
	@Cacheable(key = "'users_'+#id")
	public Optional<User> findById(Long id) throws Exception {
		return userRepository.findById(id);
	}

	@Override
	@CacheEvict(key = "'userAll'", allEntries = true)
	@Cacheable(key = "'users_'+#user.id")
	public User save(User user) throws Exception {
		return this.userRepository.save(user);
	}

	@Override
	@CacheEvict(key = "'users_'+#id", condition = "#id!=1")
	/* @CachePut(key="'users_'+#id",condition="#id!=1") */
	public void delete(Long id) throws Exception {
		this.userRepository.delete(id);
	}

	@CacheEvict(key = "'userAll'", allEntries = true)
	@Cacheable(key = "'users_'+#id")
	public void update(Long id, String userName) throws Exception {
		this.userRepository.update(id, userName);
	}

}
